import java.io.File;
import java.net.*;
import java.util.*;

import ro.pub.cs.dfsa.client.connection.AbstractClientConnection;
import ro.pub.cs.dfsa.client.connection.TCPClientConnection;
import ro.pub.cs.dfsa.server.connection.AbstractServerConnection;
import ro.pub.cs.dfsa.server.connection.TCPServerConnection;
import ro.pub.cs.dfsa.server.connection.UDPServerConnection;

public class DFSAServer extends Thread {
	public static final int MaxAccepts = 5;

	private int id;
	private AbstractServerConnection listener;
	
	private int port;
	private ArrayList<RequestProcessor> al;
	
	public DFSAServer(int port, int id) {
		this.port = port;
		this.id = id;
		this.al = new ArrayList<RequestProcessor>();
		
		File folder = new File(ServerConstants.DIRECTORY_PATH + id);
		if (!folder.exists()){
			try{
				folder.mkdir();
			} catch (Exception e){}
		}
	}
	
	public int getID(){
		return id;
	}
	
	public void run() {
		try {
			listener = new TCPServerConnection();
			listener.setServerPort(port);
			listener.createListener();
		} catch (Exception e) {
			System.err.println("Exceptie la crearea ServerSocket-ului: " + e);
			e.printStackTrace();
			return;
		}
		
		for (int i = 0; i < MaxAccepts; i++) {
			System.out.println("[TCPServer] Accepting a new connection");

			Socket clientSocket = null;
			
			try {
				AbstractClientConnection connection = listener.getClient();				
				
				RequestProcessor tst = new RequestProcessor(this.id, connection);
				
				tst.start();
				this.al.add(tst);
			} catch (Exception e) {
				System.err.println("Eroare la accept: " + e);
				e.printStackTrace();
			}
		}
		
		for (RequestProcessor tst: this.al) {
			try {
				tst.join();
			} catch (Exception e) {}
		}
		
		try {
			listener.close();
		} catch (Exception e) {
			System.err.println("ServerSocket close exception: " + e);
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]) {
		DFSAServer ts = new DFSAServer(50004, 1);
		ts.start();
		
		try {
			ts.join();
		} catch (Exception e) {}
	}
}
